using System;
using UnityEngine;
using UnityEngine.LowLevel;


public class CustomPlayerLoopSystem : MonoBehaviour
    {
        // 自定义系统类型（用于标识）
        public struct MyCustomUpdateSystem { }
    
        void Awake()
        {
            // 获取当前 PlayerLoop
            var playerLoop = PlayerLoop.GetCurrentPlayerLoop();
        
            // 插入自定义系统到 Update 之后
            InjectCustomSystem(ref playerLoop);
        
            // 应用修改后的 PlayerLoop
            PlayerLoop.SetPlayerLoop(playerLoop);
        
            Debug.Log("自定义 PlayerLoop 系统已注入");
        }
    
        void InjectCustomSystem(ref PlayerLoopSystem playerLoop)
        {
            // 查找 Update 阶段
            for (int i = 0; i < playerLoop.subSystemList.Length; i++)
            {
                if (playerLoop.subSystemList[i].type == typeof(UnityEngine.PlayerLoop.Update))
                {
                    var updateSystem = playerLoop.subSystemList[i];
                
                    // 创建自定义子系统
                    var customSystem = new PlayerLoopSystem
                    {
                        type = typeof(MyCustomUpdateSystem),
                        updateDelegate = MyCustomUpdate
                    };
                
                    // 在 Update 的子系统末尾添加
                    var newSubSystems = new PlayerLoopSystem[updateSystem.subSystemList.Length + 1];
                    System.Array.Copy(updateSystem.subSystemList, newSubSystems, updateSystem.subSystemList.Length);
                    newSubSystems[newSubSystems.Length - 1] = customSystem;
                
                    updateSystem.subSystemList = newSubSystems;
                    playerLoop.subSystemList[i] = updateSystem;
                    //添加内置循环事件
                
                    break;
                }
            }
        }

        private void FixedUpdate()
        {
            Debug.Log("FixedUpdate");
        }
        void Update()
        {
            Debug.Log("Update");
        }
        
        private void LateUpdate()
        {
            Debug.Log("LateUpdate");
        }

        static void MyCustomUpdate()
        {
            // 这个方法会在每帧 Update 之后被调用
            Debug.Log($"[CustomUpdate] Frame: {Time.frameCount}, Time: {Time.time:F2}");
        }
    
        void OnDestroy()
        {
            // 恢复默认 PlayerLoop
            PlayerLoop.SetPlayerLoop(PlayerLoop.GetDefaultPlayerLoop());
        }
    }
